package com.dm.cloud.images.ws;

import com.github.dockerjava.api.DockerClient;
import com.dm.cloud.images.mode.AppArrangeModel;
import com.dm.cloud.images.service.ImagesAppArrangeService;
import com.dm.cloud.images.service.ImagesEndpointService;
import com.dm.cloud.images.ws.callback.ContainerMonitorCallback;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.websocket.OnClose;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Slf4j
@Component
@ServerEndpoint("/api/ws/docker/app/{appCode}/container/monitor")
public class AppMonitorWebSocket extends AbstractWebSocket {

    private static ImagesEndpointService imagesEndpointService;

    @Autowired
    private static ImagesAppArrangeService imagesAppArrangeService;

    private List<DockerClient> clients=new ArrayList<>();

    @Autowired
    public void setImagesAppArrangeService(ImagesAppArrangeService imagesAppArrangeService){
        AppMonitorWebSocket.imagesAppArrangeService=imagesAppArrangeService;
    }

    @Autowired
    public void setImagesEndpointService(ImagesEndpointService imagesEndpointService){
        AppMonitorWebSocket.imagesEndpointService=imagesEndpointService;
    }

    @PostConstruct
    public void printWsStartInfo() {
        log.info("容器状态WebSocket初始化完成！");
    }


    @OnOpen
    @SneakyThrows
    public void onOpen(Session session) {
        final Map<String, String> parameters = session.getPathParameters();
        try {
            String appCode = parameters.get("appCode");
            AppArrangeModel appArranges = imagesAppArrangeService.getArrange(appCode);
            if(appArranges==null || appArranges.getArranges()==null || appArranges.getArranges().isEmpty()){
                this.onClose(session);
                return;
            }
            this.init(session);
            for (List<AppArrangeModel.AppArrangeItem> arrangeArr : appArranges.getArranges()) {
                for (AppArrangeModel.AppArrangeItem arrangeItem : arrangeArr) {
                    DockerClient client =imagesEndpointService.getClientByNodeId(arrangeItem.getNodeId());
                    ContainerMonitorCallback callback=null;
                    try {
                        callback= new ContainerMonitorCallback(session);
                        client.statsCmd(arrangeItem.getContainerId()).exec(callback);
                        this.addCallback(session, callback);
                    } catch (Exception e) {
//                        this.onClose(session);
                        //这个节点异常
                        log.error("容器异常，可能没有启动!"+arrangeItem.getId());
//                        e.printStackTrace();
                        callback.close();
                    }
                    clients.add(client);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            this.onClose(session);
        }

    }

    @OnClose
    @SneakyThrows
    public void onClose(Session session) {
        try {
            super.onClose(session);
        }catch (Exception e){}
        for (DockerClient client : clients) {
            try {
                client.close();
            }catch (Exception e){}
        }
    }

}
